﻿using System;

namespace DotNet.Common.Utilities
{
    public static class Exception
    {
        private static readonly string formatString = 
                        "Message:" + Environment.NewLine + "\t{0}" + Environment.NewLine + "----------------" + Environment.NewLine +
                           "Source:" + Environment.NewLine + "\t{1}" + Environment.NewLine + "----------------" + Environment.NewLine +
                     "StackTrace:" + Environment.NewLine + "\t{2}" + Environment.NewLine + "----------------" + Environment.NewLine +
                              "type:" + Environment.NewLine + "\t{3}" + Environment.NewLine;

        /// <summary>
        /// 格式化异常信息
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static string FormatException(System.Exception ex)
        {
            var newLine = System.Environment.NewLine;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(string.Format(formatString, ex.Message, ex.Source, ex.StackTrace, ex.GetType().FullName));
            if (ex.InnerException != null)
            {
                sb.Append(newLine);
                sb.Append(newLine);
                sb.Append("~~~~~~~~~InnerException~~~~~~~~~" + newLine);
                sb.Append(newLine);
                sb.Append(newLine);
                sb.Append(FormatException(ex.InnerException));
            }
            return sb.ToString();
        }
    }
}
